package com.itheima;

import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.regexp.internal.RE;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
@WebServlet("/ServletAdd")
public class ServletAdd extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String stuid = req.getParameter("stuid");
        String stuname = req.getParameter("stuname");
        String stusex = req.getParameter("stusex");
        String stuscore = req.getParameter("stuscore");
        HashMap<String, Student> hm = new HashMap<>();
        Student student = new Student(stuid,stuname,stusex,Integer.parseInt(stuscore));
        req.getSession().setAttribute("stu",student);
        String realPath = getServletContext().getRealPath("/stu.txt");
        File file = new File(realPath);
        if (!file.exists()){
            BufferedWriter bw = new BufferedWriter(new FileWriter(realPath,true));
            bw.write(student.getId()+":"+student.getName()+":"+student.getSex()+":"+student.getScore());
            bw.newLine();
            resp.sendRedirect(req.getContextPath()+"/add.jsp");
            bw.close();
        }else{
            BufferedReader br = new BufferedReader(new FileReader(realPath));
            String s;
            while ((s=br.readLine())!=null){
                String[] split = s.split(":");
                hm.put(split[0],new Student(split[0],split[1],split[2],Integer.parseInt(split[3])));
            }
            br.close();
            if (hm.containsKey(stuid)){
                resp.getWriter().write("已存在学生id,请重新添加...");
                resp.setHeader("Refresh","2;URL=add.jsp");
            }else{
                BufferedWriter bw = new BufferedWriter(new FileWriter(realPath,true));
                bw.write(student.getId()+":"+student.getName()+":"+student.getSex()+":"+student.getScore());
                bw.newLine();
                bw.close();
                hm.put(stuid,student);
                resp.sendRedirect(req.getContextPath()+"/add.jsp");
            }
        }


    }
}
